package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.WxSetting;
import com.ybkj.daijia.api.weixin.AccessToken;
import com.ybkj.daijia.api.weixin.WeixinUtil;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.PassengerApi;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.server.Config;
import com.ybkj.daijia.server.event.model.MemberBookTimeZhuanEvent;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.event.model.SysLowestWorkVirtualChangeEvent;
import com.ybkj.daijia.server.event.model.SysSettingChangeEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.MemberNotice;
import com.ybkj.daijia.server.model.MenuButton;
import com.ybkj.daijia.server.scheduler.ThreadControl;
import com.ybkj.daijia.server.service.MenuButtonService;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

@Controller
@RequestMapping(value = "setting")
public class SettingController {

  @Autowired
  private SettingUtils settingUtils;

  @Autowired
  private MenuButtonService menuButtonService;

  @Autowired
  private ApplicationEventMulticaster applicationEventMulticaster;

  @Autowired
  private PassengerApi passengerApi;

  @RequestMapping(value = "set", method = RequestMethod.GET)
  public String set(Model model) {

    Subject subject = SecurityUtils.getSubject();

    if (subject.isPermitted("setting")) {
      model.addAttribute("setting", settingUtils.get());

      return "setting/set";
    } else {
      throw new NoPermissionException();
    }

  }

  @RequestMapping(value = "setwx", method = RequestMethod.GET)
  public String setwx(Model model) {

    Subject subject = SecurityUtils.getSubject();

    if (subject.isPermitted("weixin")) {

      WxSetting setting = settingUtils.getWx();

      String webapp = Config.getWebapp();

      File cert = new File(String.format("%s/upload/wx/cert/apiclient_cert.p12", webapp));
      if (cert.exists()) {
        setting.setCertUrl("apiclient_cert.p12");
      }

      model.addAttribute("setting", setting);

      return "setting/setwx";
    } else {
      throw new NoPermissionException();
    }
  }

  /**
   * 上传微信公众号二维码
   *
   * @param request 请求对象
   * @param file    上传文件
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "uploadWxQrCode")
  public Map<String, Object> uploadWxQrCode(HttpServletRequest request, MultipartFile file) {

    Map<String, Object> returnMap = new HashMap<String, Object>();

    try {
      if (null == file) {
        returnMap.put("code", 1);
        returnMap.put("errorMsg", "上传的文件不能为空");
        return returnMap;
      }

      HashMap<String, String> extMap = new HashMap<String, String>();
      extMap.put("image", "gif,jpg,jpeg,png,bmp");
      String originalFilename = file.getOriginalFilename();
      String dirName = "image";
      // 检查扩展名
      String fileExt = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
      if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
        returnMap.put("code", -1);
        returnMap.put("errorMsg", "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
        return returnMap;
      }

      String path = WebUtils.getRealPath(request.getSession().getServletContext(), "/");
      String originalName = file.getOriginalFilename();
      String suffix = originalName.substring(originalName.lastIndexOf("."), originalName.length());
      String fileName = "upload/img/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID().toString() + suffix;
      File targetFile = new File(path, fileName);
      if (!targetFile.exists()) {
        targetFile.mkdirs();
      }
      file.transferTo(targetFile);

      returnMap.put("code", 0);
      returnMap.put("data", fileName);
      returnMap.put("errorMsg", "上传成功");
    } catch (Exception e) {
      e.printStackTrace();
      returnMap.put("code", -1);
      returnMap.put("errorMsg", "上传出现错误");
    }
    return returnMap;
  }

  @RequestMapping(value = "wxmenu", method = RequestMethod.GET)
  public String wxmenu(Model model) {

    Subject subject = SecurityUtils.getSubject();

    if (subject.isPermitted("weixin")) {

      List<MenuButton> buttons = menuButtonService.findByParentIsNull();

      if (!CollectionUtils.isEmpty(buttons)) {
        for (MenuButton menuButton : buttons) {
          menuButton.setSub_button(menuButtonService.findByParent(menuButton.getId()));
        }
      }


      model.addAttribute("buttons", buttons);

      return "setting/wxmenu";
    } else {
      throw new NoPermissionException();
    }

  }

  /**
   * 创建微信按钮
   *
   * @param button
   * @return
   */
  @RequestMapping(value = "createWxButton", method = RequestMethod.POST)
  public @ResponseBody
  Result<MenuButton> createWxButton(MenuButton button, @RequestParam(required = false) Long parentID) {

    Subject subject = SecurityUtils.getSubject();
    Principal principal = (Principal) subject.getPrincipal();

    if (subject.isPermitted("weixin")) {

      Result<MenuButton> result = new Result<MenuButton>();
      result.setSuccess(false);
      button.setName(StringUtils.trimToEmpty(button.getName()));
      button.setType(MenuButton.BUTTON_TYPE_CLICK);//默认为点击事件

      if (StringUtils.isBlank(button.getName())) {
        result.setMessage("按钮名称不能为空");
      } else if (button.getName().length() > 8) {
        result.setMessage("按钮名字太长");
      } else {
        if (parentID == null || parentID == 0) {//没有父级

          long count = menuButtonService.countByParent(null);

          if (count < 3) {
            button = menuButtonService.insertRecord(button);
            result.setSuccess(true);
            result.setMessage("添加成功");
            result.setObject(button);

            String detail = "【%s】创建微信按钮";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);
          } else {
            result.setMessage("可创建最多 3 个一级菜单");
          }

        } else {

          long count = menuButtonService.countByParent(parentID);
          if (count < 5) {
            MenuButton parent = menuButtonService.findOne(parentID);
            if (null == parent) {
              result.setMessage("父菜单不存在");
            } else {
              button.setParentId(parentID);
              button = menuButtonService.insertRecord(button);
              result.setSuccess(true);
              result.setMessage("添加成功");
              result.setObject(button);

              String detail = "【%s】创建微信按钮";
              OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
              applicationEventMulticaster.multicastEvent(operationLogEvent);
            }
          } else {
            result.setMessage("每个一级菜单下可创建最多 5 个二级菜单");
          }
        }

      }


      return result;
    } else {
      throw new NoPermissionException();
    }
  }

  /**
   * 修改
   *
   * @param name
   * @param id
   * @return
   */
  @RequestMapping(value = "modifyWxButton", method = RequestMethod.POST)
  public @ResponseBody
  Result<MenuButton> modifyWxButton(String name, Long id) {

    Subject subject = SecurityUtils.getSubject();
    Principal principal = (Principal) subject.getPrincipal();
    if (subject.isPermitted("weixin")) {

      Result<MenuButton> result = new Result<MenuButton>();
      result.setSuccess(false);

      name = StringUtils.trimToEmpty(name);

      if (StringUtils.isBlank(name)) {
        result.setMessage("按钮名称不能为空");
      } else if (name.length() > 8) {
        result.setMessage("按钮名字太长");
      } else {
        MenuButton btn = menuButtonService.findOne(id);
        if (null == btn) {
          result.setMessage("按钮不存在或者已被删除");
        } else {
          btn.setName(name);
          menuButtonService.updateByPrimaryKey(btn);

          result.setMessage("修改成功");
          result.setSuccess(true);
          result.setObject(btn);

          String detail = "【%s】修改微信按钮";
          OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
          applicationEventMulticaster.multicastEvent(operationLogEvent);
        }
      }

      return result;
    } else {
      throw new NoPermissionException();
    }
  }


  @RequestMapping(value = "removeWxButton", method = RequestMethod.POST)
  public @ResponseBody
  Result<MenuButton> removeWxButton(Long id) {

    Subject subject = SecurityUtils.getSubject();
    Principal principal = (Principal) subject.getPrincipal();

    if (subject.isPermitted("weixin")) {

      Result<MenuButton> result = new Result<MenuButton>();
      result.setSuccess(false);

      if (null == id) {
        result.setMessage("参数错误");
      } else {

        MenuButton btn = menuButtonService.findOne(id);
        if (null == btn) {
          result.setMessage("按钮不存在或者已被删除");
        } else {
          menuButtonService.delete(btn);
          result.setMessage("删除成功");
          result.setSuccess(true);

          String detail = "【%s】删除微信按钮";
          OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
          applicationEventMulticaster.multicastEvent(operationLogEvent);
        }
      }

      return result;
    } else {
      throw new NoPermissionException();
    }
  }

  @RequestMapping(value = "setWxButton", method = RequestMethod.POST)
  public @ResponseBody
  Result<MenuButton> setWxButton(Long id, String type,
                                 @RequestParam(required = false) String key,
                                 @RequestParam(required = false) String url,
                                 @RequestParam(required = false) String message) {

    Subject subject = SecurityUtils.getSubject();
    Principal principal = (Principal) subject.getPrincipal();

    if (subject.isPermitted("weixin")) {

      Result<MenuButton> result = new Result<MenuButton>();
      result.setSuccess(false);

      if (null == id) {
        result.setMessage("参数错误");
      } else {

        MenuButton btn = menuButtonService.findOne(id);
        if (null == btn) {
          result.setMessage("按钮不存在或者已被删除");
        } else {
          if (type.equals(MenuButton.BUTTON_TYPE_CLICK)) {
            btn.setType(type);
            btn.setKey(key);
            menuButtonService.updateByPrimaryKey(btn);

            result.setMessage("设置成功");
            result.setSuccess(true);
            result.setObject(btn);

            String detail = "【%s】设置微信按钮";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);
          } else if (type.equals(MenuButton.BUTTON_TYPE_VIEW)) {
            btn.setType(type);
            btn.setUrl(url);
            menuButtonService.updateByPrimaryKey(btn);

            result.setMessage("设置成功");
            result.setSuccess(true);
            result.setObject(btn);

            String detail = "【%s】设置微信按钮";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);
          }
        }
      }

      return result;
    } else {
      throw new NoPermissionException();
    }

  }

  /**
   * 发布微信
   *
   * @return
   */
  @RequestMapping(value = "publishWxMenu", method = RequestMethod.POST)
  public @ResponseBody
  Result<MenuButton> publishWxMenu() {

    Subject subject = SecurityUtils.getSubject();
    Principal principal = (Principal) subject.getPrincipal();

    if (subject.isPermitted("weixin")) {

      Result<MenuButton> result = new Result<MenuButton>();
      result.setSuccess(false);

      WxSetting setting = settingUtils.getWx();
      if (StringUtils.isBlank(setting.getWxAppId()) || StringUtils.isBlank(setting.getWxAppSecret())) {
        result.setMessage("请先选择 系统 ＝》 微信配置 填写 微信公众平台提供给您的 AppId 和 AppSecret");
      } else {

        List<MenuButton> buttons = menuButtonService.findByParentIsNull();

        if (CollectionUtils.isEmpty(buttons)) {
          result.setMessage("请先创建菜单并设置对应操作");
        } else {
          AccessToken accessToken = WeixinUtil.getAccessToken(setting.getWxAppId(), setting.getWxAppSecret());

          StringBuilder sb = new StringBuilder();
          sb.append("{");
          sb.append("\"button\":[");
          for (int i = 0; i < buttons.size(); i++) {

            MenuButton menuButton = buttons.get(i);

            sb.append("{");
            sb.append("\"name\"").append(":").append("\"").append(menuButton.getName()).append("\"").append(",");

            List<MenuButton> subButtons = menuButtonService.findByParent(menuButton.getId());

            if (CollectionUtils.isEmpty(subButtons)) {

              sb.append("\"type\"").append(":").append("\"").append(menuButton.getType()).append("\"").append(",");

              if (MenuButton.BUTTON_TYPE_CLICK.equals(menuButton.getType())) {
                sb.append("\"key\"").append(":").append("\"").append(menuButton.getKey()).append("\"");
              } else if (MenuButton.BUTTON_TYPE_VIEW.equals(menuButton.getType())) {
                sb.append("\"url\"").append(":").append("\"").append(menuButton.getUrl()).append("\"");
              }


            } else {
              sb.append("\"sub_button\":[");
              for (int j = 0; j < subButtons.size(); j++) {
                MenuButton menuButton2 = subButtons.get(j);
                sb.append("{");
                sb.append("\"name\"").append(":").append("\"").append(menuButton2.getName()).append("\"").append(",");
                sb.append("\"type\"").append(":").append("\"").append(menuButton2.getType()).append("\"").append(",");
                if (MenuButton.BUTTON_TYPE_CLICK.equals(menuButton2.getType())) {
                  sb.append("\"key\"").append(":").append("\"").append(menuButton2.getKey()).append("\"");
                } else if (MenuButton.BUTTON_TYPE_VIEW.equals(menuButton2.getType())) {
                  sb.append("\"url\"").append(":").append("\"").append(menuButton2.getUrl()).append("\"");
                }
                sb.append("}");

                if (j < subButtons.size() - 1) {
                  sb.append(",");
                }

              }
              sb.append("]");

            }
            sb.append("}");

            if (i < buttons.size() - 1) {
              sb.append(",");
            }

          }
          sb.append("]");
          sb.append("}");

          int ret = WeixinUtil.createMenu(sb.toString(), accessToken.getToken());

          if (ret == 0) {
            result.setMessage("发布成功");
            result.setSuccess(false);

            String detail = "【%s】发布微信";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);
          } else {
            result.setMessage("发布失败，错误代码为：" + ret);
          }

        }

      }
      return result;
    } else {
      throw new NoPermissionException();
    }
  }


  @RequestMapping(value = "set", method = RequestMethod.POST)
  public String set(Setting setting, Model model) {
    Subject subject = SecurityUtils.getSubject();
    Principal principal = (Principal) subject.getPrincipal();

    if (subject.isPermitted("setting")) {
      Setting oldsetting = settingUtils.get();
//			if(oldsetting.getWorkBegin()!=setting.getWorkBegin()){
//				//改变司机单量计时
//				try {
////					Scheduler daysched= Config.getDaysched();
////					Scheduler monthsched= Config.getMonthsched();
//					
////					JobKey dayJobKey = new JobKey("day", "dayGroupName");
////					TriggerKey dayTriggerKey = new TriggerKey("dayTrigger", "dayTriggerGroupName");
////					daysched.pauseTrigger(dayTriggerKey);//停止触发器  
////					daysched.unscheduleJob(dayTriggerKey);//移除触发器  
////					daysched.deleteJob(dayJobKey);
//					
//
////					JobKey monthJobKey = new JobKey("month","monthGroupName");
////					TriggerKey monthTriggerKey = new TriggerKey("monthTrigger", "monthTriggerGroupName");
////					monthsched.pauseTrigger(monthTriggerKey);
////					monthsched.unscheduleJob(monthTriggerKey);
////					monthsched.deleteJob(monthJobKey);
//					
//				
//					
////					CronTrigger trigger =  (CronTrigger) TriggerBuilder.newTrigger()
////							.withIdentity(dayTriggerKey)
////							.withSchedule(CronScheduleBuilder.cronSchedule("0 0 "+setting.getWorkBegin()+" * * ?"))
////							.startNow()
////							.build();
//					
//					
////					JobDetail jobDetail = JobBuilder.newJob(ClearDayOrderNums.class).withIdentity(dayJobKey).build();//new JobDetail("day","dayGroupName",clearDayOrderNums.class);  
//					
////					daysched = new StdSchedulerFactory().getScheduler();  
////					daysched.scheduleJob(jobDetail,trigger);
////					daysched.start();
////					Config.setDaysched(daysched);
//					
////					jobDetail = JobBuilder.newJob(ClearMonthOrderNums.class).withIdentity(monthJobKey).build();//new JobDetail("month","monthGroupName",clearMonthOrderNums.class);  
//					
////					CronTrigger trigger2 = (CronTrigger) TriggerBuilder.newTrigger()
////							.withIdentity(monthTriggerKey)
////							.withSchedule(CronScheduleBuilder.cronSchedule("0 0 "+setting.getWorkBegin()+" 1 * ? "))
////							.startNow()
////							.build();
//							
//					
//					
////					monthsched = new org.quartz.impl.StdSchedulerFactory().getScheduler();  
////					monthsched.scheduleJob(jobDetail,trigger2);
////					monthsched.start();
////					Config.setMonthsched(monthsched);
//					
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//				
//			}

      ServiceSetting serviceSetting = ServiceUtil.checkOpen();

      oldsetting.setWorkBegin(setting.getWorkBegin());
      oldsetting.setCompanyWebURL(setting.getCompanyWebURL());
      oldsetting.setInfoFee(setting.getInfoFee());
      oldsetting.setInfoFeeZhuan(setting.getInfoFeeZhuan());
      oldsetting.setInfoFeeFreight(setting.getInfoFeeFreight());
      oldsetting.setInfoFeeErrand(setting.getInfoFeeErrand());
      oldsetting.setInfoFeeCityline(setting.getInfoFeeCityline());
      oldsetting.setInfoFeeType(setting.getInfoFeeType());
      oldsetting.setCouponTicheng(setting.isCouponTicheng());
      oldsetting.setUpPlatformInfo(setting.isUpPlatformInfo());
      oldsetting.setDoubleFactor(setting.isDoubleFactor());
      oldsetting.setNearDriversKm(setting.getNearDriversKm());
      oldsetting.setNearDriversAmount(setting.getNearDriversAmount());
      oldsetting.setNearDriversKm2(setting.getNearDriversKm2());
      oldsetting.setNearDriversAmount2(setting.getNearDriversAmount2());
      oldsetting.setNearFreightDriversKm(setting.getNearFreightDriversKm());
      oldsetting.setRevokeTime(setting.getRevokeTime());
      oldsetting.setBookTimeZhuanxian(setting.getBookTimeZhuanxian());
      oldsetting.setAllowCallDriver(setting.isAllowCallDriver());
      oldsetting.setWhichServicePhone(setting.getWhichServicePhone());
      oldsetting.setAgreement(setting.getAgreement());
      oldsetting.setBusinessContent(setting.getBusinessContent());
      oldsetting.setShareTitle(setting.getShareTitle());
      oldsetting.setShareContent(setting.getShareContent());
      oldsetting.setShareTwodCode(setting.getShareTwodCode());
      oldsetting.setAboutWeb(setting.getAboutWeb());
      oldsetting.setAboutPhone(setting.getAboutPhone());
      oldsetting.setAboutLogo(setting.getAboutLogo());
      oldsetting.setMoenyBase(setting.getMoenyBase());
      oldsetting.setStartQuota(setting.getStartQuota());
      oldsetting.setEndQuota(setting.getEndQuota());
      oldsetting.setRemarks(setting.getRemarks());
      oldsetting.setMemberApplyContent(setting.getMemberApplyContent());
      oldsetting.setErrandValuationMethod(setting.getErrandValuationMethod());
      oldsetting.setKuaicheAutoCancelOrder(setting.isKuaicheAutoCancelOrder());
      oldsetting.setKuaicheAutoCancelOrderTime(setting.getKuaicheAutoCancelOrderTime());
      oldsetting.setZhuanxianAutoCancelOrder(setting.isZhuanxianAutoCancelOrder());
      oldsetting.setZhuanXianAutoCancelOrderTime(setting.getZhuanXianAutoCancelOrderTime());
      boolean lwvChange = false;
      if (!oldsetting.getLowestWorkVirtual().equals(setting.getLowestWorkVirtual())) {
        lwvChange = true;
      }
      oldsetting.setLowestWorkVirtual(setting.getLowestWorkVirtual());

      boolean appChange = false;
      if (oldsetting.isAllowRushOrder() != setting.isAllowRushOrder() || oldsetting.isAllowWorkCar() != setting.isAllowWorkCar() ||
              oldsetting.isAllowWorkCarZhuandan() != setting.isAllowWorkCarZhuandan() || oldsetting.isAllowDriverZhuandan() != setting.isAllowDriverZhuandan() ||
              oldsetting.isAllowDriverCancel() != setting.isAllowDriverCancel() || oldsetting.isMustToPlace() != setting.isMustToPlace() ||
              oldsetting.isMustMemberInfo() != setting.isMustMemberInfo() || oldsetting.isAllowModifyCash() != setting.isAllowModifyCash() ||
              oldsetting.isAllowBaoxiao() != setting.isAllowBaoxiao() || oldsetting.isInsurancesShow() != setting.isInsurancesShow() ||
              oldsetting.isOpenHelpPay() != setting.isOpenHelpPay() || oldsetting.isJustPrice() != setting.isJustPrice()) {

        appChange = true;
      }
      if (oldsetting.getBookTimeZhuan() != setting.getBookTimeZhuan()) {
        List<Passenger> passengerList = passengerApi.findPassenger(principal, null, null, null, null, null, null,
                null, null, null, null, null, null);
        MemberBookTimeZhuanEvent bookTimeZhuanEvent = new MemberBookTimeZhuanEvent(new MemberNotice(), passengerList);
        applicationEventMulticaster.multicastEvent(bookTimeZhuanEvent);
      }

      //司机端
//			oldsetting.setRushOrderKm(setting.getRushOrderKm());
      oldsetting.setBookTimeZhuan(setting.getBookTimeZhuan());
      oldsetting.setAllowWorkCar(setting.isAllowWorkCar());
      oldsetting.setAllowWorkCarZhuandan(setting.isAllowWorkCarZhuandan());
      oldsetting.setAllowDriverZhuandan(setting.isAllowDriverZhuandan());
      oldsetting.setAllowDriverCancel(setting.isAllowDriverCancel());
      oldsetting.setMustToPlace(setting.isMustToPlace());
      oldsetting.setMustMemberInfo(setting.isMustMemberInfo());
      oldsetting.setAllowModifyCash(setting.isAllowModifyCash());
      oldsetting.setAllowBaoxiao(setting.isAllowBaoxiao());
      oldsetting.setAllowHelppayNe(setting.isAllowHelppayNe());
      oldsetting.setInsurancesShow(setting.isInsurancesShow());
      oldsetting.setEmployApplyImgNessesary(setting.isEmployApplyImgNessesary());
      oldsetting.setOpenHelpPay(setting.isOpenHelpPay());
      oldsetting.setJustPrice(setting.isJustPrice());
      oldsetting.setArriveToPlaceKm(setting.getArriveToPlaceKm());
      oldsetting.setNearPaotuiOrdersKm(setting.getNearPaotuiOrdersKm());
      oldsetting.setErrandGrabAmount(setting.getErrandGrabAmount());
      oldsetting.setZhuanYuyueMax(setting.getZhuanYuyueMax());
      oldsetting.setZhuanYuyueTime(setting.getZhuanYuyueTime());
      oldsetting.setDriverBindPhone(setting.isDriverBindPhone());
      //用户端
      oldsetting.setPaotuiFixPrice(setting.isPaotuiFixPrice());
      oldsetting.setZhuanchePrePay(setting.isZhuanchePrePay());
      oldsetting.setDaijiaPrePay(setting.isDaijiaPrePay());
      oldsetting.setPaotuiPrePay(setting.isPaotuiPrePay());

      String webUrl = setting.getWebUrl().trim();
      //系统网址
      if (StringUtils.isNotBlank(setting.getWebUrl())) {

        if (webUrl.endsWith("/")) {
          webUrl = webUrl.substring(0, webUrl.length() - 1);
        }
        oldsetting.setWebUrl(webUrl);
      }

      //安卓司机端
      if (StringUtils.isNotBlank(setting.getAndroidDriver())) {
        String androidDriver = setting.getAndroidDriver().trim();
        if (androidDriver.endsWith("/")) {
          androidDriver = androidDriver.substring(0, androidDriver.length() - 1);
        }
        oldsetting.setAndroidDriver(androidDriver);
      }else {
        oldsetting.setAndroidDriver(webUrl+"/download/driver.html");
      }

      //安卓客户端
      if (StringUtils.isNotBlank(setting.getAndroidCustomer())) {
        String androidCustomer = setting.getAndroidCustomer().trim();
        if (androidCustomer.endsWith("/")) {
          androidCustomer = androidCustomer.substring(0, androidCustomer.length() - 1);
        }
        oldsetting.setAndroidCustomer(androidCustomer);
      }else {
        oldsetting.setAndroidCustomer(webUrl+"/download/customer.html");
      }

      //充值金额配置
      if (null != setting.getPayCash1()) {
        oldsetting.setPayCash1(setting.getPayCash1());
      }
      if (null != setting.getPayCash2()) {
        oldsetting.setPayCash2(setting.getPayCash2());
      }
      if (null != setting.getPayCash3()) {
        oldsetting.setPayCash3(setting.getPayCash3());
      }
      if(null != setting.getDriverRebateMoney()) {
        oldsetting.setDriverRebateMoney(setting.getDriverRebateMoney());
      }
      //支付宝支付配置
      if (StringUtils.isNotBlank(setting.getAlipayPartnerID())) {
        oldsetting.setAlipayPartnerID(setting.getAlipayPartnerID().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setAlipayPartnerID("");
        }
      }

      if (StringUtils.isNotBlank(setting.getAlipaySellerID())) {
        oldsetting.setAlipaySellerID(setting.getAlipaySellerID().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setAlipaySellerID("");
        }
      }

      if (StringUtils.isNotBlank(setting.getAlipayPartnerPrivKey())) {
        oldsetting.setAlipayPartnerPrivKey(setting.getAlipayPartnerPrivKey().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setAlipayPartnerPrivKey("");
        }
      }

      if (StringUtils.isNotBlank(setting.getAlipayPartnerPublicKey())) {
        oldsetting.setAlipayPartnerPublicKey(setting.getAlipayPartnerPublicKey().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setAlipayPartnerPublicKey("");
        }
      }

      //微信支付配置
      if (StringUtils.isNotBlank(setting.getWxAppID())) {
        oldsetting.setWxAppID(setting.getWxAppID().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setWxAppID("");
        }
      }

      if (StringUtils.isNotBlank(setting.getWxAppSecret())) {
        oldsetting.setWxAppSecret(setting.getWxAppSecret().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setWxAppSecret("");
        }
      }

      if (StringUtils.isNotBlank(setting.getWxAppIDEmploy())) {
        oldsetting.setWxAppIDEmploy(setting.getWxAppIDEmploy().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setWxAppIDEmploy("");
        }
      }

      if (StringUtils.isNotBlank(setting.getWxAppSecretEmploy())) {
        oldsetting.setWxAppSecretEmploy(setting.getWxAppSecretEmploy().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setWxAppSecretEmploy("");
        }
      }

      if (StringUtils.isNotBlank(setting.getWxPartnerID())) {
        oldsetting.setWxPartnerID(setting.getWxPartnerID().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setWxPartnerID("");
        }
      }

      if (StringUtils.isNotBlank(setting.getWxPartnerKey())) {
        oldsetting.setWxPartnerKey(setting.getWxPartnerKey().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setWxPartnerKey("");
        }
      }

      if (StringUtils.isNotBlank(setting.getWxPartnerIDEmploy())) {
        oldsetting.setWxPartnerIDEmploy(setting.getWxPartnerIDEmploy().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setWxPartnerIDEmploy("");
        }
      }

      if (StringUtils.isNotBlank(setting.getWxPartnerKeyEmploy())) {
        oldsetting.setWxPartnerKeyEmploy(setting.getWxPartnerKeyEmploy().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setWxPartnerKeyEmploy("");
        }
      }

      if (StringUtils.isNotBlank(setting.getWxAppKEY())) {
        oldsetting.setWxAppKEY(setting.getWxAppKEY().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setWxAppKEY("");
        }
      }
      if (StringUtils.isNotBlank(setting.getMerId())) {
        oldsetting.setMerId(setting.getMerId().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setMerId("");
        }
      }
      if (StringUtils.isNotBlank(setting.getAcpsdkSignCertPath())) {
        oldsetting.setAcpsdkSignCertPath(setting.getAcpsdkSignCertPath().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setAcpsdkSignCertPath("");
        }
      }
      if (StringUtils.isNotBlank(setting.getAcpsdkSignCertPwd())) {
        oldsetting.setAcpsdkSignCertPwd(setting.getAcpsdkSignCertPwd().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setAcpsdkSignCertPwd("");
        }
      }
      if (StringUtils.isNotBlank(setting.getAcpProdEnc())) {
        oldsetting.setAcpProdEnc(setting.getAcpProdEnc().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setAcpProdEnc("");
        }
      }
      if (StringUtils.isNotBlank(setting.getAcpProdMiddle())) {
        oldsetting.setAcpProdMiddle(setting.getAcpProdMiddle().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setAcpProdMiddle("");
        }
      }
      if (StringUtils.isNotBlank(setting.getAcpProdRoot())) {
        oldsetting.setAcpProdRoot(setting.getAcpProdRoot().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setAcpProdRoot("");
        }
      }

      //翼支付
      if (StringUtils.isNotBlank(setting.getMerchantId())) {
        oldsetting.setMerchantId(setting.getMerchantId().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setMerchantId("");
        }
      }
      if (StringUtils.isNotBlank(setting.getMerKey())) {
        oldsetting.setMerKey(setting.getMerKey().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setMerKey("");
        }
      }
      if (StringUtils.isNotBlank(setting.getRiskcontrolinfo())) {
        oldsetting.setRiskcontrolinfo(setting.getRiskcontrolinfo().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setRiskcontrolinfo("");
        }
      }
      if (StringUtils.isNotBlank(setting.getMchPwd())) {
        oldsetting.setMchPwd(setting.getMchPwd().trim());
      } else {
        if (serviceSetting.isZhifu()) {
          oldsetting.setMchPwd("");
        }
      }


      //派单设置
      oldsetting.setPaidanKm(setting.getPaidanKm());
      oldsetting.setAutoOfflineTime(setting.getAutoOfflineTime());

      oldsetting.setAutoPaidanKm1(setting.getAutoPaidanKm1());
      oldsetting.setAutoPaidanKm2(setting.getAutoPaidanKm2());
      oldsetting.setAutoPaidanKm3(setting.getAutoPaidanKm3());
      oldsetting.setAutoPaidanTime1(setting.getAutoPaidanTime1());
      oldsetting.setAutoPaidanTime2(setting.getAutoPaidanTime2());
      oldsetting.setAutoPaidanTime3(setting.getAutoPaidanTime3());

      oldsetting.setRushOrderKm1(setting.getRushOrderKm1());
      oldsetting.setRushOrderKm2(setting.getRushOrderKm2());
      oldsetting.setRushOrderKm3(setting.getRushOrderKm3());
      oldsetting.setRushOrderTime1(setting.getRushOrderTime1());
      oldsetting.setRushOrderTime2(setting.getRushOrderTime2());
      oldsetting.setRushOrderTime3(setting.getRushOrderTime3());

      oldsetting.setAutoPaidan(setting.isAutoPaidan());
      oldsetting.setAutoPaidanZhuanche(setting.isAutoPaidanZhuanche());
      oldsetting.setAutoPaidanZhuanxian(setting.isAutoPaidanZhuanxian());
      oldsetting.setAllowRushOrder(setting.isAllowRushOrder());
      oldsetting.setAllowRushOrderZhuanche(setting.isAllowRushOrderZhuanche());
      oldsetting.setAllowRushOrderZhuanxian(setting.isAllowRushOrderZhuanxian());
      oldsetting.setAllowRushOrderErrand(setting.isAllowRushOrderErrand());
      oldsetting.setAllowRushOrderFreight(setting.isAllowRushOrderFreight());

      ThreadControl.SysAutoRunning = setting.isAutoPaidan();
      ThreadControl.autoPaidanZhuanche = setting.isAutoPaidanZhuanche();

      //推送设置
      if (StringUtils.isNotBlank(setting.getGetuiAppID())) {
        oldsetting.setGetuiAppID(setting.getGetuiAppID().trim());
      } else {
        oldsetting.setGetuiAppID("");
      }

      if (StringUtils.isNotBlank(setting.getGetuiAppKey())) {
        oldsetting.setGetuiAppKey(setting.getGetuiAppKey().trim());
      } else {
        oldsetting.setGetuiAppKey("");
      }

      if (StringUtils.isNotBlank(setting.getGetuiMaster())) {
        oldsetting.setGetuiMaster(setting.getGetuiMaster().trim());
      } else {
        oldsetting.setGetuiMaster("");
      }
      //推送设置
      if (StringUtils.isNotBlank(setting.getGetuiAppIDGeneral())) {
        oldsetting.setGetuiAppIDGeneral(setting.getGetuiAppIDGeneral().trim());
      } else {
        oldsetting.setGetuiAppIDGeneral("");
      }

      if (StringUtils.isNotBlank(setting.getGetuiAppKeyGeneral())) {
        oldsetting.setGetuiAppKeyGeneral(setting.getGetuiAppKeyGeneral().trim());
      } else {
        oldsetting.setGetuiAppKeyGeneral("");
      }

      if (StringUtils.isNotBlank(setting.getGetuiMasterGeneral())) {
        oldsetting.setGetuiMasterGeneral(setting.getGetuiMasterGeneral().trim());
      } else {
        oldsetting.setGetuiMasterGeneral("");
      }

      if (StringUtils.isNotBlank(setting.getGetuiMemberAppID())) {
        oldsetting.setGetuiMemberAppID(setting.getGetuiMemberAppID().trim());
      } else {
        oldsetting.setGetuiMemberAppID("");
      }

      if (StringUtils.isNotBlank(setting.getGetuiMemberAppKey())) {
        oldsetting.setGetuiMemberAppKey(setting.getGetuiMemberAppKey().trim());
      } else {
        oldsetting.setGetuiMemberAppKey("");
      }

      if (StringUtils.isNotBlank(setting.getGetuiMemberMaster())) {
        oldsetting.setGetuiMemberMaster(setting.getGetuiMemberMaster().trim());
      } else {
        oldsetting.setGetuiMemberMaster("");
      }

      if (StringUtils.isNotBlank(setting.getJiguangEmployAppKey())) {
        oldsetting.setJiguangEmployAppKey(setting.getJiguangEmployAppKey().trim());
      } else {
        oldsetting.setJiguangEmployAppKey("");
      }
      if (StringUtils.isNotBlank(setting.getJiguangEmployMasterSecret())) {
        oldsetting.setJiguangEmployMasterSecret(setting.getJiguangEmployMasterSecret().trim());
      } else {
        oldsetting.setJiguangEmployMasterSecret("");
      }
      if (StringUtils.isNotBlank(setting.getJiguangEmployAppKeyGeneral())) {
        oldsetting.setJiguangEmployAppKeyGeneral(setting.getJiguangEmployAppKeyGeneral().trim());
      } else {
        oldsetting.setJiguangEmployAppKeyGeneral("");
      }
      if (StringUtils.isNotBlank(setting.getJiguangEmployMasterSecretGeneral())) {
        oldsetting.setJiguangEmployMasterSecretGeneral(setting.getJiguangEmployMasterSecretGeneral().trim());
      } else {
        oldsetting.setJiguangEmployMasterSecretGeneral("");
      }

      if (StringUtils.isNotBlank(setting.getJiguangPassengerAppKey())) {
        oldsetting.setJiguangPassengerAppKey(setting.getJiguangPassengerAppKey().trim());
      } else {
        oldsetting.setJiguangPassengerAppKey("");
      }
      if (StringUtils.isNotBlank(setting.getJiguangPassengerMasterSecret())) {
        oldsetting.setJiguangPassengerMasterSecret(setting.getJiguangPassengerMasterSecret().trim());
      } else {
        oldsetting.setJiguangPassengerMasterSecret("");
      }


      //安全设置
      oldsetting.setFilterStr(setting.getFilterStr());
      //自动下单
      if(setting.getAutoCancelOrderTime()!=null){
        oldsetting.setAutoCancelOrderTime(setting.getAutoCancelOrderTime());
        oldsetting.setAutoCancelOrder(setting.isAutoCancelOrder());
      }
      //随机红包
      oldsetting.setRandomRedPacket(setting.isRandomRedPacket());
      oldsetting.setRandomRedPacketCycle(setting.getRandomRedPacketCycle());
      oldsetting.setRandomRedPacketMoney((setting.getRandomRedPacketMoney()));

      //百度ak
      oldsetting.setBaiduKey(setting.getBaiduKey());

      settingUtils.set(oldsetting);

      Setting newSetting = settingUtils.get();
      model.addAttribute("setting", newSetting);
      model.addAttribute("saveSuccess", "saveSuccess");

      if (appChange) {//如果app设置改变
        SysSettingChangeEvent settingChangeEvent = new SysSettingChangeEvent(newSetting, null);
        applicationEventMulticaster.multicastEvent(settingChangeEvent);
      }

      if (lwvChange && newSetting.getLowestWorkVirtual() != 0) {//如果司机最低上班余额改变
        SysLowestWorkVirtualChangeEvent sysLowestWorkVirtualChangeEvent = new SysLowestWorkVirtualChangeEvent(newSetting);
        applicationEventMulticaster.multicastEvent(sysLowestWorkVirtualChangeEvent);
      }

      String detail = "【%s】修改了系统配置";
      OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
      applicationEventMulticaster.multicastEvent(operationLogEvent);

      return "setting/set";
    } else {
      throw new NoPermissionException();
    }
  }

  @RequestMapping(value = "setwx", method = RequestMethod.POST)
  public String setwx(WxSetting setting, Model model) {

    Subject subject = SecurityUtils.getSubject();

    if (subject.isPermitted("weixin")) {

      if (StringUtils.isNotBlank(setting.getWxToken())) {
        setting.setWxToken(setting.getWxToken().trim());
      }
      if (StringUtils.isNotBlank(setting.getWxAppId())) {
        setting.setWxAppId(setting.getWxAppId().trim());
      }
      if (StringUtils.isNotBlank(setting.getWxAppSecret())) {
        setting.setWxAppSecret(setting.getWxAppSecret().trim());
      }
      if (StringUtils.isNotBlank(setting.getWxPartnerId())) {
        setting.setWxPartnerId(setting.getWxPartnerId().trim());
      }
      if (StringUtils.isNotBlank(setting.getWxPartnerKey())) {
        setting.setWxPartnerKey(setting.getWxPartnerKey().trim());
      }
      if (StringUtils.isNotBlank(setting.getWxServer())) {
        setting.setWxServer(setting.getWxServer().trim());
      }
      if (StringUtils.isNotBlank(setting.getWxQrCode())) {
        setting.setWxQrCode(setting.getWxQrCode().trim());
      }
      if (StringUtils.isNotBlank(setting.getWxSmallQrCode())) {
        setting.setWxSmallQrCode(setting.getWxSmallQrCode().trim());
      }

      settingUtils.setWx(setting);

      WxSetting wxSetting = settingUtils.getWx();

      String webapp = Config.getWebapp();

      File cert = new File(String.format("%s/upload/wx/cert/apiclient_cert.p12", webapp));
      if (cert.exists()) {
        wxSetting.setCertUrl("apiclient_cert.p12");
      }

      model.addAttribute("setting", wxSetting);
      model.addAttribute("saveSuccess", "saveSuccess");

      return "setting/setwx";
    } else {
      throw new NoPermissionException();
    }

  }
}
